package com.llkj.qingnianguoxue.circle;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputType;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.llkj.qingnianguoxue.R;
import com.llkj.qingnianguoxue.adapter.GroupDetailAdapter;
import com.llkj.qingnianguoxue.base.BaseActivity;
import com.llkj.qingnianguoxue.base.ConstantUserInfo;
import com.llkj.qingnianguoxue.base.MyApplication;
import com.llkj.qingnianguoxue.bean.CircleDetailBean;
import com.llkj.qingnianguoxue.bean.CircleListBean;
import com.llkj.qingnianguoxue.bean.RxBusChatBean;
import com.llkj.qingnianguoxue.bean.eventbean.MemberManagerEvent;
import com.llkj.qingnianguoxue.http.HttpMethod;
import com.llkj.qingnianguoxue.mine.MyFriendsActivity;
import com.llkj.qingnianguoxue.util.DialogUtil;
import com.llkj.qingnianguoxue.util.GridSpacingItemDecoration;
import com.llkj.qingnianguoxue.util.GsonUtil;
import com.llkj.qingnianguoxue.util.ImageLoadingUtil;
import com.llkj.qingnianguoxue.util.KeyBoardUtil;
import com.llkj.qingnianguoxue.util.RxBus;
import com.llkj.qingnianguoxue.util.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.im.android.api.JMessageClient;

import static com.llkj.qingnianguoxue.circle.CircleOwnerDetailActivity.IS_REPORT;

public class GroupDetailActivity extends BaseActivity {

    @BindView(R.id.ivCirclePic)
    protected ImageView mIvCirclePic;//圈子图片
    @BindView(R.id.tvCircleName)
    protected TextView mTvCircleName;//圈子名字
    @BindView(R.id.ivModifyName)
    ImageView ivModifyName;
    @BindView(R.id.tvCircleDescription)
    protected TextView mTvCircleDescription;//圈子简介
    @BindView(R.id.ivModifyDescription)
    ImageView ivModifyDescription;
    @BindView(R.id.tvMemberCount)
    protected TextView mTvMemberCount;//成员数量
    @BindView(R.id.ivGo)
    protected ImageView mIvMoreCount;//成员数量

    @BindView(R.id.rlWarning)
    protected RelativeLayout mRlWarning;//警告
    @BindView(R.id.rlDenied)
    protected RelativeLayout mRlDenied;//禁言
    @BindView(R.id.rlMemberManager)
    protected RelativeLayout mRlMemberManager;//成员管理
    @BindView(R.id.tvDissolveCircle)
    TextView btnDissolveCircle;//底部按钮
    @BindView(R.id.rvMember)
    protected RecyclerView mRvMember;//成员列表
    private GroupDetailAdapter mMemberAdapter;//适配器
    private List<CircleListBean.CircleBean> mMemberData;//成员数据
    private int mModityOption;//修改选项,1名称，2简介
    private String mPrice,mCircleDuration,mIsPush,mCircleCoverUrl;//圈子价格，圈子时限，圈子到时提醒,圈子封面url

    private String mCircleId,mCircleOwnId,mCircleName,mGroupChatId;//圈子id,圈子群主id,圈子名,圈子群聊id

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_group_detail);
        setTitle("圈子", true, TITLE_TYPE_IMG, R.drawable.icon_back, false, -1, -1);
        initStatusbar(TSATUSBAR_TYPE_BLACK_TEXT,rlTitle,R.color.gray_bar);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);

        initView();
        initListener();

        loadWaitDialog();
        HttpMethod.circleDetail(this,this,mCircleId);
    }

    private void initView(){
        Intent intent = getIntent();
        mCircleId = intent.getStringExtra("circleId");

        mRvMember.setLayoutManager(new GridLayoutManager(this,5));
        mRvMember.addItemDecoration(new GridSpacingItemDecoration(5, 10, false));
        mMemberData = new ArrayList<>();
        mMemberAdapter = new GroupDetailAdapter(R.layout.item_circle_by_me,mMemberData);
        mRvMember.setAdapter(mMemberAdapter);
    }

    private void initListener(){
        mRvMember.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                if(i<mMemberData.size()-1){
                    CircleListBean.CircleBean item = mMemberData.get(i);
                    //进入个人介绍
                    Bundle bundle = new Bundle();
                    bundle.putBoolean(IS_REPORT,true);
                    bundle.putString("ownerId",item.getId());
                    bundle.putString("circleId",mCircleId);
                    startActivity(CircleOwnerDetailActivity.class,bundle);
                }else{
                    //邀请
                    Bundle bundle = new Bundle();
                    bundle.putString("circleId",mCircleId);
                    startActivity(InviteFriendsActivity.class,bundle);
                }
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void modifyPriceDuration(MemberManagerEvent event){
        if(event!=null){
            mPrice = event.price;
            mCircleDuration = event.circleDuration;
            mIsPush = event.isPush;
        }
    }

    @OnClick({R.id.ivModifyName, R.id.ivModifyDescription, R.id.rlMoreMembers,
            R.id.rlWarning, R.id.rlDenied, R.id.rlMemberManager, R.id.tvDissolveCircle})
    public void onClick(View view){
        Bundle bundle = null;
        switch (view.getId()){
            case R.id.ivModifyName://修改圈名
                mModityOption = 1;
                setModifyContent("修改圈名",mTvCircleName.getText().toString());
                break;
            case R.id.ivModifyDescription://修改圈简介
                mModityOption = 2;
                setModifyContent("修改圈简介",mTvCircleDescription.getText().toString());
                break;
            case R.id.rlMoreMembers://全部成员
                bundle = new Bundle();
                bundle.putString("groupId", mGroupChatId);
                startActivity(CircleMemberActivity.class,bundle);
                break;
            case R.id.rlWarning://警告
                bundle = new Bundle();
                bundle.putInt("type", 0);
                bundle.putString("groupChatId", mGroupChatId);
                startActivity(MemberWarningActivity.class,bundle);
                break;
            case R.id.rlDenied://禁言
                bundle = new Bundle();
                bundle.putInt("type", 1);
                bundle.putString("groupChatId", mGroupChatId);
                startActivity(MemberWarningActivity.class,bundle);
                break;
            case R.id.rlMemberManager://会费管理
                MemberManagerActivity.startActivity(this,mCircleId,mGroupChatId,mPrice,mCircleDuration,mIsPush);
                break;
            case R.id.tvDissolveCircle://解散圈子/退出
                String uid = MyApplication.getInstance().sputil.getString(ConstantUserInfo.USER_ID);
                if(uid.equals(mCircleOwnId)) {//解散圈子
                    DialogUtil.dialogConfirm(this, "确定解散圈子吗？", null, "取消", "确定", new DialogUtil.DialogClickListener() {

                        @Override
                        public void dialogClick(int type) {
                            KeyBoardUtil.hideSoftKeyboard(GroupDetailActivity.this);
                            if (type == 1) {//确定
                                loadWaitDialog();
                                HttpMethod.dissolution(GroupDetailActivity.this, GroupDetailActivity.this,mGroupChatId,mCircleId);
                            }
                        }
                    }).show();
                }else{//退出圈子
                    DialogUtil.dialogConfirm(this, "确定退出圈子吗？", null, "取消", "确定", new DialogUtil.DialogClickListener() {

                        @Override
                        public void dialogClick(int type) {
                            KeyBoardUtil.hideSoftKeyboard(GroupDetailActivity.this);
                            if (type == 1) {//确定
                                loadWaitDialog();
                                HttpMethod.secede(GroupDetailActivity.this, GroupDetailActivity.this,mGroupChatId,mCircleId);
                            }
                        }
                    }).show();
                }
                break;
        }
    }

    private void setModifyContent(String title, String content){
        DialogUtil.modifyGroupDialog(this, InputType.TYPE_CLASS_TEXT, title, content, new DialogUtil.DialogRechargeClickListener() {
            @Override
            public void rechargeClick(int type, String content) {
                KeyBoardUtil.hideSoftKeyboard(GroupDetailActivity.this);
                if(type==1){
                    if(mModityOption==1){
                        mTvCircleName.setText(content);
                    }else{
                        mTvCircleDescription.setText(content);
                    }
                    modifyCircleData();
                }
            }
        }).show();
    }

    /**
     * 获取成员
     */
    private void getMemberData(){
        loadWaitDialog();
        HttpMethod.circleMember(this,this,"",mGroupChatId, String.valueOf(1));
    }

    private void modifyCircleData(){
        loadWaitDialog();
        String modifyContent = null;
        if(mModityOption==1){
            modifyContent = mTvCircleName.getText().toString();
            HttpMethod.circleEdit(this,this,mGroupChatId,modifyContent,null,null,null,null);
        }else{
            modifyContent = mTvCircleDescription.getText().toString();
            HttpMethod.circleEdit(this,this,mGroupChatId,null,null,null,modifyContent,null);
        }
    }

    @Override
    protected void onhttpSuccess(String data, int method) {
        super.onhttpSuccess(data, method);
        if (method == HttpMethod.HTTP_CIRCLE_DETAIL) {//圈子详情
            CircleDetailBean detailBean = GsonUtil.GsonToBean(data,CircleDetailBean.class);
            if(detailBean!=null){
                mCircleOwnId = detailBean.getUid();
                mCircleName = detailBean.getName();
                mGroupChatId = detailBean.getHx_id();
                mPrice = detailBean.getPrice();
                mCircleDuration = detailBean.getCycle();
//                mIsPush = detailBean.
                tvTitle.setText(mCircleName);
                mCircleCoverUrl = detailBean.getImg();
                ImageLoadingUtil.loadingCircleBorderImg(mIvCirclePic,mCircleCoverUrl, R.color.transparent);
                mTvCircleName.setText(mCircleName);
                mTvCircleDescription.setText("简介："+detailBean.getDescribe());

                btnDissolveCircle.setVisibility(View.VISIBLE);
                String uid = MyApplication.getInstance().sputil.getString(ConstantUserInfo.USER_ID);
                if(uid.equals(mCircleOwnId)){
                    btnDissolveCircle.setText("解散圈子");
                    mRlWarning.setVisibility(View.VISIBLE);//警告
                    mRlDenied.setVisibility(View.VISIBLE);;//禁言
                    mRlMemberManager.setVisibility(View.VISIBLE);//
                    ivModifyName.setVisibility(View.VISIBLE);
                    ivModifyDescription.setVisibility(View.VISIBLE);
                }else{
                    btnDissolveCircle.setText("退出圈子");
                }

                loadWaitDialog();
                getMemberData();
            }
        }else if (method == HttpMethod.HTTP_CIRCLE_MEMBER) {//圈子成员
            try {
                CircleListBean circleListBean = GsonUtil.GsonToListBean(data, CircleListBean.class);
                if (circleListBean != null) {
                    mMemberData.clear();
                    if(circleListBean.getMember().size()<41){
                        mMemberData.addAll(circleListBean.getMember());
                        mMemberData.add(new CircleListBean.CircleBean());
                    }else{
                        mMemberData.addAll(circleListBean.getMember().subList(0,41));
                    }
                    mTvMemberCount.setText("共"+circleListBean.getMember().size()+"人");
                    mMemberAdapter.notifyDataSetChanged();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else if(method == HttpMethod.HTTP_CIRCLE_EDIT){// 修改缴费金额与费用时限,圈子名称，简介
            ToastUtil.makeLongText(this,"修改成功");
            if(mModityOption==1){//修改圈子名
                String circleName =  mTvCircleName.getText().toString();
                RxBusChatBean bean = new RxBusChatBean();
                bean.setType(1);
                bean.setContent(circleName);
                RxBus.getInstance().post(bean);
            }else{//修改圈子简介

            }
        }else if(method == HttpMethod.HTTP_CIRCLE_SECEDE || method == HttpMethod.HTTP_CIRCLE_DISSOLUTION){//退出圈子
            RxBus.getInstance().post(ConstantUserInfo.REFRESH_CIRCLE);
            try {
                JMessageClient.deleteGroupConversation(Long.parseLong(mGroupChatId));
            }catch (Exception e){}
            myFinish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
